// 柯里化是把一个多参数函数转化成一个嵌套的一元函数的过程
function add() {
    let args = Array.prototype.slice.call(arguments);
    const _add = function () {
        //需要扩展类数组对象到数组里
        args.push(...arguments)
        // console.log(args)
        return _add
    }

    _add.valueOf = function () {
        return args.reduce((a, b) => a + b, 0)
    }
    return _add
}

console.log(add(1, 2)(3))

function sum(...args) {
    return args.reduce((a, b) => a + b, 0)
}

function curry(fn) {
    return function curried(...args) {
        //如果参数达到length 直接执行原函数
        if (args.length >= fn.length) {
            return fn.apply(this, args);
        } else {
            return function (...args2) {
                return curried.apply(this, args.concat(args2))
            }
        }
    }
}

function curry1(fn, ...args) {
    return fn.length <= args.length ? fn(...args) : curry1.bind(null, fn, ...args);
}

function currying(fn) {
    let args = [];
    const _sum = function (...newArgs) {
        if (newArgs.length) {
            args = [...args, ...newArgs]
            return _sum
        } else {
            let val = fn.apply(this, args)
            _sum.clean()
            return val
        }
    }
    _sum.toString = function () {
        return fn.apply(null, args)
    }
    _sum.clean = function () {
        args = []
    }
    return _sum
}

let _sum = currying(sum);

console.log(_sum(1, 1)(3)(2)())
